<?php
namespace Admin\Controller;
use Think\Controller;
use Redis;
require_once ROOT . "/Common/ColoudSearch/CloudsearchClient.php";
require_once ROOT . "/Common/ColoudSearch/CloudsearchIndex.php";
require_once ROOT . "/Common/ColoudSearch/CloudsearchDoc.php";

class TestController extends CommonController {
	public function index(){
		$this->display();
	}

	
	// 更新fileSize字段单位为字节
	public function size() {
		// 参数
		$page = I("get.page", 1);
		$limit = I("get.ltd", 10);
		$next = ++$page;

		// 模型
		$model = D("hash");

		$count = $model->cache()->count();
		$total = ceil($count/$limit);
		if ($total < $page) {
			$this->show("<h1>Finished ALL {$total} pages.</h1>");
		} else {
			// 构建更新数据
			$list = $model->page($page, $limit)->field('id,fileSize')->select();
			$file = ROOT . "/fileSize.UPDATE.SQL";
			$sql = "UPDATE hash SET fileSize = CASE id ";
			foreach ($list as $v) {
				$sizeArray = explode(" ", $v['fileSize']);
				switch ($sizeArray[1]) {
					case 'GB':
						$size = $sizeArray[0] *1024 *1024 *1024;
						break;

					case 'MB':
						$size = $sizeArray[0] *1024 *1024;
						break;

					case 'KB':
						$size = $sizeArray[0] *1024;
						break;

					case 'B':
					default:
						$size = $sizeArray[0];
						break;
				}
				$size = ceil($size);
				$ids .= empty($ids) ? "{$v['id']}" : ", {$v['id']}";
				$sql .= sprintf("WHEN %s THEN %s ", $v['id'], $size);
			}
			$sql .= "END WHERE id IN ($ids);\r\n";
			
			// 写入数据库，并生成sql文件
			if ( false == $model->execute($sql)) {
				$this->show("<h1><a href=\"__URL__/size/page/{$page}\">Click try again!</a></h1>");
			} else {
				file_put_contents($file, $sql, FILE_APPEND);
				$this->show("<h2>UPDATE {$page}/{$total} Succeeded.</h2> <small>{$ids}</small><script language=\"javascript\" type=\"text/javascript\">window.location.href=\"__URL__/size/page/{$next}\";</script>");
			}			
		}
	}

	/**
	 * Pinging Service
	 * @param string $page 页数
	 * @param string $ltd 单页限量
	 * @param string $id 最小id
	 * @access public
	 * @author FrankKung <Frank@kofj.net>
	 */
	public function ping() {
		// 参数
		$page = I('get.page',1);
		$ltd = I('get.ltd',10);
		$id = I('get.id',1);
		$next = ++$page;

		$where['id'] = array('gt',$id);
		$order['id'] = "asc";
		$model = D("Ping");
		$list = $model->where($where)->field('id,hash')->page($page, $ltd)->order($order)->select();
		//var_dump($list,$model);
		foreach ($list as $v) {
			$ret = ping($v['hash'], $v['id'], 'baidu');
			$ids .= empty($ids) ? "{$v['id']}" : ", {$v['id']}";
			$model->where(array('id'=>$v['id']))->save($ret);
		}

		$this->show("<h2>UPDATE Succeeded.</h2> <small>{$ids}</small><script language=\"javascript\" type=\"text/javascript\">window.location.href=\"__URL__/ping/page/{$next}\";</script>");
	}

	/**
	 * Update Source
	 * @access public
	 * @author FrankKung <Frank@kofj.net>
	 */
	public function git() {
		echo exec("git pull", $exec);
		var_dump($exec);
	}

	/**
	 * Parse torrent files
	 * @access public
	 * @author FrankKung <Frank@kofj.net>
	 */
	public function torrent() {
		//if (!IS_CLI) {echo "Just run in CLI." ;return 0;}

		import('ORG.Util.Torrent');
		// 文件路径
		$filePath = "F:/912.rar/912/";
		$bot = "CodEiT.cn Torrent File Parse Bot";
		$db = 'mysql://root:@localhost/torrent';
		$replace = array('_', ' ', '-', '{', '}', '\\', '[', ']', '(', ')', ':', '!', '?', '$', '#', '@', '~', '%', '&', '*', '+', '=', ';', '/', '.', ',,');
		$model = M('Hash', '', $db);

		$per = 100;
		$count = $per;
		 while ( $count > 0) {
			$where['bot'] = '';
			$list = $model->where($where)->field('hash')->page($page,$per)->select();
			$sign['bot'] = $bot;
			$list['_logic'] = 'OR';
			$count = $model->where($list)->save($sign);
			unset($list['_logic']);

			mb_internal_encoding("utf-8");  // 假定你的程序是gbk的 
			mb_http_output("gbk"); // 要输出成 utf-8 的
			ob_start('mb_output_handler'); // 只需这样就可以了
			echo "查询{$count}条记录成功\r\n";
			
			foreach ($list as $k => $v) {
				$fullPath = $filePath . strtoupper($v['hash']) . '.torrent';
				$Parse = new \Torrent($fullPath);
				$data['hash'] = $v['hash'];
				$data['title'] = $Parse->name();
				$data['magnet'] = $Parse->magnet();
				foreach ($Parse->content() as $i => $v) {
					$data['file'] .= "{$i},";
				}
				$data['fileNumber'] = count($Parse->content());
				$data['fileSize'] = $Parse->size();
				$keywords = str_replace($replace, ',', $Parse->name());
				$data['keywords'] = str_replace(',,', ',', $keywords);
				$data['time'] = time();
				$id = $model->save($data);
				unset($data);
				echo "解析种子：{$fullPath}", ($id > 0) ? "[成功]<span>\r\n" : "[失败]\r\n" ;
				flush();
				if (ob_get_level() > 0) {
					ob_flush();
				}
				//flush();

			}

			$total = $model->where($where)->count();
			echo "<h2>解析{$count}个种子文件完成,剩余{$total},进入下一页：{$next}</h2>";
			//"<script language=\"javascript\" type=\"text/javascript\">window.location.href=\"/Admin/index/torrent/page/{$next}\";</script>";
			flush();
			if (ob_get_level() > 0) {
				ob_flush();
			}
		}
	}

	public function info() {
		phpinfo();
	}

	/**
	 * 阿里云搜索测试
	 * @access public
	 * @author FrankKung <Frank@kofj.net>
	 */
	public function test() {
		//
		$client = new \CloudsearchClient(
			C('CS.ACCESSKEYID'), 
			C('CS.SECRET'), 
			array('host' => C('CS.HOST')),
			C('CS.KEY_TYPE')
		);
		// $app = new \CloudsearchIndex(C('CS.APP_NAME'), $client);

		// 查看当前应用的状态
		// echo $app->status();

		// 获取当前应用的所有错误信息。
		// echo $app->getErrorMessage();

		// 获取所有的应用信息
		// echo $app->listIndexes();

		$doc = new \CloudsearchDoc(C('CS.APP_NAME'), $client);

		// 或$doc->update($json), $doc->remove($json)
		// 注意，参数1可以为一个json的string或者为一个数组，
		// 结构为：
		// [{fields:{fieldname1: fieldvalue1, fieldname2: fieldvalue2, ...}, cmd: ADD|DELETE|UPDATE},...]
		// 参数2为您创建要push数据的表名。
		// 如果需要多表的数据push，请先push附表的数据，然后在push主表的数据。
		$page = I('get.page',1);
		$ret = M("Hash")->field('id,hash,title,file,keywords,fileSize,fileNumber,time,pageRank,isBad')->page($page, 20)->select();
		//var_dump($ret);
		foreach ($ret as $v) {
			$data[] = array(
				'fields'	=> $v,
				'cmd'		=> 'ADD',
			);
		}
		$statusJson = $doc->add($data, 'main');
		$status = json_decode($statusJson, true);
		var_dump($status['status']);
	}

	public function setcache() {
		$key = I('get.key');
		$vo = I('get.vo');
		var_dump($key,$vo);
		S($key, $vo);
	}

	public function getcache() {
		$key = I('get.key');
		$vo = S($key);
		var_dump($key, $vo);
	}

	public function testcache() {
		var_dump(S('name'));
	}

	public function rand() {
		$redis= new \Redis();
		$redis->connect('127.0.0.1',6379);
		$randMember = $redis->sRandMember('maindb',20);
		//var_dump($randMember);
		$Hash = D('Hash');
		$map['hash'] = array('in', $randMember);
		$members = $Hash->where($map)->field('hash,title,fileSize')->select();
		var_dump($members);
	}
}
